﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text;
using VitCode.ObjectResolutionHelper;

namespace VitCode.ObjectSettingApp
{
    public class DbSettingHelper:BaseHelper
    {

        public StringCollection scSystemType;
        
        /*
         

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AmsCore_Area]') AND type in (N'U'))
DROP TABLE [dbo].[AmsCore_Area]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AmsCore_Area]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[AmsCore_Area](
	[Id] [uniqueidentifier] NOT NULL,
	[Name] [nvarchar](50) NULL,
	[Code] [nvarchar](50) NULL,
	[Memo] [nvarchar](200) NULL,
	[ParentId] [uniqueidentifier] NULL,
	[OrderId] [varchar](500) NULL,
	[CreateUserId] [uniqueidentifier] NULL,
	[ImportNum] [varchar](50) NULL,
	[LastEditUserId] [uniqueidentifier] NULL,
	[LastEditDate] [datetime] NULL,
	[IsLogicDelete] [int] NULL,
	[KeyWord] [nvarchar](100) NULL,
 CONSTRAINT [PK_Area] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
         */
        public string GetClassContext(Type objType, string tableNameHeadString)
        {
            m_Checker.CheckClass(objType);
            PropertyInfo[] pros = LookUpClassHelper.GetPros(objType);
            var sb = new StringBuilder();
            NameValueCollection nvcMap = GetDbTypeMapping();
            var nvcProLenMap = GetProLenMapping();
            string tableName = tableNameHeadString + "_" + objType.Name;
            sb.Append(@"IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + tableName +
                      @"]') AND type in (N'U'))
DROP TABLE [dbo].[" + tableName +
                      @"]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" +
                      tableName + @"]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[" + tableName + @"](");
            var keyFiledName = "Id";
            foreach (PropertyInfo p in pros)
            {
                if (p.Name == HistoryKeyInfo.H_ID)
                    keyFiledName = p.Name;
                sb.Append(GetProContext(p, nvcMap, nvcProLenMap) + ", \r\n");
            }
            sb.Append(@" CONSTRAINT [PK_" + objType.Name +
                      @"] PRIMARY KEY CLUSTERED 
(
	["+keyFiledName+@"] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO");
            return sb.ToString();
        }

        private string GetProContext(PropertyInfo pro, NameValueCollection nvcTypeMapping, NameValueCollection nvcProLenMapping)
        {
            var proType = pro.PropertyType;
            if (pro.PropertyType.Name.ToLower().StartsWith("nullable"))
            {
                proType = Nullable.GetUnderlyingType(pro.PropertyType);
            }
            string dbTypeName = nvcTypeMapping.Get(proType.ToString());
            string colName = pro.Name;
            if (string.IsNullOrEmpty(dbTypeName))
            {
                colName += BaseDataKeyInfo.ID;
                dbTypeName = "uniqueidentifier";
            }

            var proLen = "";
            if (proType == typeof(string))
            {
                if (pro.Name.ToLower().IndexOf("path") > -1 || pro.Name.ToLower().IndexOf("url") > -1)
                    proLen = "200";
            }
            var tempStr = nvcProLenMapping.Get(pro.Name);
            if (!string.IsNullOrEmpty(tempStr)) proLen = tempStr;
            if (!string.IsNullOrEmpty(proLen))
            {
                dbTypeName = "nvarchar(" + proLen + ")";
            }

            string val = "[" + colName + "] " + dbTypeName;
            //[Id] [int] IDENTITY(1,1) NOT NULL,
            
            if(pro.Name == BaseDataKeyInfo.ID || pro.Name == HistoryKeyInfo.H_ID)
            {
                if(proType == typeof(int))
                {
                    val += " IDENTITY(1,1)";
                }
                val += " not NULL";
            }
            else
                val += " NULL";
            return val;
        }
    }
}
